package com.cwits.wifi.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseActivity;
import com.cwits.wifi.manager.ControlManager;
import com.cwits.wifi.ui.dialog.OneDialog;
import com.cwits.wifi.ui.service.CommunicationService;
import com.cwits.wifi.update.UpDateTool;
import com.cwits.wifi.update.UpdateChecker;
import com.cwits.wifi.util.IAction;
import com.cwits.wifi.util.PreferencesHelper;
import com.jieli.lib.stream.beans.StateInfo;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Locale;

/**
 * 版本信息
 * Created by Administrator on 2016/2/26.
 * <p/>
 * showIsUpdateDialog() 是否下载最新固件提示框
 * <p/>
 * showInstallDialog()  下载完成是否安装提示框
 * <p/>
 * showProgress(String str) 加载框 str为要显示的文字  mProgressDialog.dismiss()使加载框消失
 */
public class VersionActivity extends BaseActivity implements UpdateChecker.IUpdateCheckerListener, View.OnClickListener {
    private RelativeLayout mBack, mRlWaring;
    private LinearLayout mLL_update;
    private ImageView mImCheckHf;
    private TextView mVersion_id, mDevice_id, mTvVersion, mTvCheckSf;
    private String mVersion_info, mDevice_info;
    private boolean mIsGetVerisonInfo = false;
    private boolean mIsGetDeviceInfo = false;
    private AlertDialog updateDialog;
    private ProgressDialog mProgressDialog;
    private AlertDialog installDialog;
    private boolean isUpdate = false;
    private boolean isConnect = false;
    private OneDialog oneDialog;
    private Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0x12345:
                    //接收版本号信息
                    mIsGetVerisonInfo = true;
                    if (mIsGetDeviceInfo == true) {
                        mVersion_id.setText(mVersion_info);
                        mDevice_id.setText(mDevice_info);
                        hideProgressDialog();
                    }

                    break;
                case 0x12346:
                    //获取设备号信息
                    mIsGetDeviceInfo = true;
                    if (mIsGetVerisonInfo == true) {
                        mVersion_id.setText(mVersion_info);
                        mDevice_id.setText(mDevice_info);
                        hideProgressDialog();
                    }
                    break;
            }
            ;
        }

    };

    @Override
    public void onWiFiState(boolean isAutoDisable, int state) {
        super.onWiFiState(isAutoDisable, state);
        switch (state) {
            case 1:
                break;
            case 2:
                connectError();
                break;
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_GET_VERSION_INFO)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_GET_VERSION_INFO);
                mVersion_info = stateInfo.getParam()[0];
                mIsGetVerisonInfo = true;
                mVersion_id.setText(mVersion_info);
                PreferencesHelper.putStringValue(context.getApplicationContext(), "soft_id", mVersion_info);
                if (mIsGetDeviceInfo)
                    hideProgressDialog();


            } else if (action.equals(ACTION_GET_DEVICE_INFO)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_GETDEVICE_INFO);
                mDevice_info = stateInfo.getParam()[0];
                mIsGetDeviceInfo = true;
                mDevice_id.setText(mDevice_info);
                if (mIsGetVerisonInfo)
                    hideProgressDialog();


            } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable() && netInfo.isConnected()
                        && netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    ///////网络连接
                    //showToastLong("网络连接");

                    if (isUpdate) {
                        autoCheckUpdate();

                    }
                } else {
                    ////////网络断开
                    // showToastLong("网络断开");
                }
            }

        }
    };


    @Override
    protected void onStart() {
        super.onStart();
    }

    private void registerGetVersionAndDeviceInfo() {
        IntentFilter intentFilter = new IntentFilter(IAction.ACTION_GET_DEVICE_INFO);
        intentFilter.addAction(IAction.ACTION_GET_VERSION_INFO);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(mReceiver, intentFilter);
    }

    private void unRegisterGetVersionAndDeviceInfo() {
        this.unregisterReceiver(mReceiver);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.version_infolayout);
        initView();
        mHandler = new Handler();
        registerGetVersionAndDeviceInfo();
        if (mApplication.getIsOffLineMode() == false) {
            //已经连接设备wifi
            isConnect = true;
            showProcessDialog();
            mRlWaring.setVisibility(View.GONE);
        } else {
            //没有连接设备wifi
            mRlWaring.setVisibility(View.VISIBLE);
            //showToast("对不起，没有连接168设备WiFi！");
        }

    }

    private void initView() {
        mProgressDialog = new ProgressDialog(this);
        mBack = (RelativeLayout) findViewById(R.id.left_imageview);
        mImCheckHf = (ImageView) findViewById(R.id.version_im_check_hw);
        mTvCheckSf = (TextView) findViewById(R.id.version_tv_check_sf);
        mLL_update = (LinearLayout) findViewById(R.id.version_ll_text);
        mVersion_id = (TextView) findViewById(R.id.version_id);
        mDevice_id = (TextView) findViewById(R.id.device_id);
        mTvVersion = (TextView) findViewById(R.id.version_tv_banben);
        mRlWaring = (RelativeLayout) findViewById(R.id.version_rl_warring);
        mTvVersion.setText(getAppInfo());
        mBack.setOnClickListener(this);
        mImCheckHf.setOnClickListener(this);
        mTvCheckSf.setOnClickListener(this);
        mLL_update.setOnClickListener(this);

    }

    private String getAppInfo() {
        try {
            String pkName = this.getPackageName();
            String versionName = this.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            int versionCode = this.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            return versionName;
        } catch (Exception e) {
        }
        return null;
    }


    @Override
    protected void onResume() {
        super.onResume();

        if (mApplication.getIsOffLineMode() == false) {
            ControlManager.getInstance().sendCommand("2", "0550", "0");
            ControlManager.getInstance().sendCommand("2", "0551", "0");
        } else {
            //do nothing;

        }

    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_imageview:
                finish();
                break;
            case R.id.version_ll_text:
                break;
            case R.id.version_im_check_hw:
                if (mApplication.getIsOffLineMode() == false) {
                    //已经连接设备wifi
                    //showToastLong("当前固件是最新固件");
                    String download_str = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("downLoad_soft_id", "xxx");
                    String soft_id = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("soft_id", "xxx");
                    String down_path = PreferencesHelper.getSharedPreferences(VersionActivity.this).getString("downLoad_soft_path", "xxx");
                    if (soft_id.equals(download_str) || !download_str.equals("xxx") || !soft_id.equals("xxx") || !down_path.equals("xxx")) {
                        //不需要更新
                        showToastLong(getString(R.string.version_zxgj));
                    } else {
                        //需要更新

                        showInstall();
                    }
                } else {
                    //没有连接设备wifi
                    showToast(getString(R.string.please_connect));
                }

                break;
            case R.id.version_tv_check_sf:
                isUpdate = true;
                showProcessDialog(getString(R.string.version_bbjc));
                if (mApplication.getIsOffLineMode()) {
                    //is
                    // mProgressDialog.dismiss();
                    autoCheckUpdate();
                } else {
                    //no
                    disconnectDevice();
                    mApplication.setIsOffLineMode(true);
                    mApplication.setRealCamera(false);
                    mApplication.setIsNeedReconnect(true);

                }
                //showToastLong("当前软件版本是最新软件版本");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterGetVersionAndDeviceInfo();
    }

    /**
     * app版本更新检查接口
     */
    private void autoCheckUpdate() {
        isUpdate = false;
        resetTimeOutStatus();
        checkNetTimeOut();
        // �����°汾���
        UpdateChecker checker = new UpdateChecker(this);
        checker.addUpdateCheckerListener(this);
        checker.execute(new URL[0]);

    }

    /**
     * 是否下载dialog
     */
    private void showIsUpdateDialog() {


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(this, R.layout.dialog_update_one_btn,
                null);
        TextView tvText = (TextView) view.findViewById(R.id.dialog_update_one_tv);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_update_one_rl);
        builder.setView(view);

        updateDialog = builder.create();
        updateDialog.setCanceledOnTouchOutside(false);
        updateDialog.setCancelable(false);
        tvText.setText(getString(R.string.version_fxgj));
        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //查看
                updateDialog.dismiss();

            }
        });

        updateDialog.setView(view, 0, 0, 0, 0);
        updateDialog.show();
        builder.setCancelable(true);
    }

    /**
     * 下载成功是否安装dialog
     */
    private void showInstall() {
        oneDialog = new OneDialog(VersionActivity.this, getString(R.string.version_xzgj_sucess), installListener);
        oneDialog.show();
    }

    private View.OnClickListener installListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_update_one_rl:

                    oneDialog.dismiss();
                    new Thread(uploadFTPServer).start();
                    showProgress(getString(R.string.version_gjsz));

                    break;

            }
        }
    };

    private void showInstallDialog() {


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(this, R.layout.dialog_update_one_btn,
                null);
        TextView tvText = (TextView) view.findViewById(R.id.dialog_update_one_tv);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_update_one_rl);
        builder.setView(view);

        installDialog = builder.create();
        installDialog.setCanceledOnTouchOutside(false);
        installDialog.setCancelable(false);
        tvText.setText(getString(R.string.version_xzgj_sucess));
        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                new Thread(uploadFTPServer).start();
                installDialog.dismiss();
                showProgress(getString(R.string.version_gjsz));
            }
        });

        installDialog.setView(view, 0, 0, 0, 0);
        installDialog.show();
        builder.setCancelable(false);
    }

    private void showProgress(String str) {

        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
        //mpDialog.setTitle("提示");//设置标题
        mProgressDialog.setMessage(str);
        mProgressDialog.setIndeterminate(false);//设置进度条是否为不明确

        mProgressDialog.setCancelable(false);//设置进度条是否可以按退回键取消

        //设置点击进度对话框外的区域对话框不消失
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
    }

    /**
     * 检查当前网络是否可用
     *
     * @param
     * @return
     */

    public boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private final Runnable uploadFTPServer = new Runnable() {
        @Override
        public void run() {
            connectFTP(INSIDE_FTP_HOST_NAME, 21, INSIDE_FTP_USER_NAME, INSIDE_FTP_PASSWORD);
        }
    };

    /**
     * connect FTP,上传最新固件升级
     */
    private void connectFTP(String add, int port, String name, String paw) {
        FTPClient mFTPClient = new FTPClient();
        mFTPClient.setControlEncoding("GBK");
        mFTPClient.setDefaultPort(port);
        try {
            mFTPClient.connect(add);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
            try {
                if (mFTPClient.login(name, paw)) {


                    InputStream bis = new FileInputStream(PreferencesHelper.getSharedPreferences(VersionActivity.this).getString("downLoad_soft_path", "xxx"));
                    mFTPClient.enterLocalPassiveMode();
                    mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                    mFTPClient.setBufferSize(1024 * 1024 * 5); //5M
                    //boolean issucess = mFTPClient.deleteFile("JL_AC51.txt");

                    if (mFTPClient.storeFile("JL_AC51.bfu", bis)) {
                        // Dbug.d(tag, "upload file success!");
                        String recordState = CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS);
                        if (ARGS_IN_RECORDING.equals(recordState)) {
                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_RESTART_DEVICE, ARGS_RESTART_DEVICE);
                    } else {
                        // Dbug.e(tag, "upload file failed!");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (mFTPClient.isConnected()) {
                    try {
                        mFTPClient.disconnect();
                        //Dbug.d(tag, "FTPClient is disconnected success!");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            // Dbug.w(tag, "Reply code is not a positive completion response.");
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mProgressDialog != null && mProgressDialog.isShowing())
                    mProgressDialog.dismiss();
                clearAllInfo();
            }
        });
    }

    private void clearAllInfo() {
        disconnectDevice();
    }

    @Override
    public void onUpdateCheckResult(boolean needUpdate, UpdateChecker.AppVersionInfo verInfo) {
        {
            // TODO Auto-generated method stub
            if (isTimeOut) {//网络延迟
                showToast(getString(R.string.version_wlcs));
                return;
            }
            hideProgressDialog();
            if (null == verInfo) {
                showToast(getString(R.string.version_not_update));
                return;
            }
            String version = verInfo.mVersionURL;

            final String str = version;
            if (needUpdate) {

                String message = "";
                try {
                    String path = Environment.getExternalStorageDirectory()
                            .getAbsolutePath()
                            + "/lipeibao/168cardev/"
                            + "VersionFiles/"
                            + "cwcex_version_desc_"
                            + String.valueOf(verInfo.mVersionCode) + ".xml";
                    File file = new File(path);

                    if (file.exists()) {

                        InputStream in = new FileInputStream(file);

                        HashMap<String, String> map = UpDateTool.parse(in);
                        String key = Locale.getDefault().getLanguage() + "_"
                                + Locale.getDefault().getCountry();
                        if (map.containsKey(key)) {
                            message = map.get(key);
                        } else {
                            // 默认提示中文信息
                            if(map.containsKey("en_US")){
                                message = map.get("en_US");
                            }else{
                                message = map.get(getString(R.string.version_update));
                            }
                        }
                    } else {
                        message = getString(R.string.update_remind);

                    }
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setCancelable(false);
                // final Dialog builder = new Dialog(getApplicationContext());
                View view = View.inflate(getApplicationContext(),
                        R.layout.dialog_update, null);
                TextView remind = (TextView) view
                        .findViewById(R.id.dialog_up_title);
                TextView msg_info = (TextView) view
                        .findViewById(R.id.dialog_up_msg);
                TextView textview_cancle = (TextView) view
                        .findViewById(R.id.dialog_up_canale);
                TextView textview_ok = (TextView) view
                        .findViewById(R.id.dialog_up_ok);
                //remind.setText(getString(R.string.update) + verInfo.mVersionName);
                // msg_info.setText(R.string.update_remind);
                msg_info.setText(message);
                textview_ok.setText(R.string.download_now);
                textview_cancle.setText(R.string.download_cancle);
                // RelativeLayout cancleRl = (RelativeLayout) view
                // .findViewById(R.id.dialog_del_ok);
                // RelativeLayout okRl = (RelativeLayout) view
                // .findViewById(R.id.dialog_del_cancle);

                builder.setView(view);

                final AlertDialog dialog = builder.create();

                textview_ok.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        dialog.dismiss();
                        if (null != str) {
                            Uri url = Uri.parse(str);
                            Intent intent = new Intent(Intent.ACTION_VIEW, url);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            VersionActivity.this.startActivity(intent);
                        } else {
                            Toast.makeText(VersionActivity.this,
                                    getString(R.string.download_failed),
                                    Toast.LENGTH_SHORT).show();
                            finish();
                        }

                    }
                });

                textview_cancle.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.setView(view, 0, 0, 0, 0);
                dialog.show();
            } else {
                showToast(getString(R.string.version_not_update));
            }


        }

    }
}
